package com.fourGirlsAndADude.mobileDRT;

import java.util.ArrayList;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.att.intern.webservice.Incident;
import com.att.intern.webservice.Webservice;
import com.att.intern.webservice.Webservice.TokenInvalidException;

public class SearchResultsActivity extends SherlockListActivity {
	private String userName;
	private String token;
	private String eventName;
	private String authType;
	private int eventYear;
	private ArrayList<Incident> incidents;
	private Webservice webservice;
	private String reportType;
	private View mSearchStatusView;
	private TextView mSearchStatusMessageView;
	private View mSearchFormView;
	private ListView list;
	private TextView error;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_results);
		webservice = LoginActivity.webService;

		Intent intent = getIntent();
		userName = intent.getStringExtra("USERNAME");
		authType = intent.getStringExtra("AUTHORIZATION_TYPE");
		token = intent.getStringExtra("SESSION_TOKEN");
		eventName = intent.getStringExtra("EVENT_NAME");
		eventYear = intent.getIntExtra("EVENT_YEAR", 0);
		System.out.println("Year: " + eventYear);
		System.out.println("Token: " + token);
		System.out.println("Name: " + eventName);
		reportType = intent.getStringExtra("REPORT_TYPE");

		TextView header = (TextView) findViewById(R.id.sra_header);
		ImageView imageView = (ImageView) findViewById(R.id.header_image);
		if (reportType.equals("ADMIN")) {
			imageView.setImageResource(R.drawable.ic_action_copy);
			header.setText(R.string.title_admin);
		} else if (reportType.equalsIgnoreCase("CRE")) {
			imageView.setImageResource(R.drawable.ic_action_folder_open);
			header.setText(R.string.title_cre);
		}
		mSearchFormView = findViewById(R.id.search_form);
		mSearchStatusView = findViewById(R.id.search_status);
		mSearchStatusMessageView = (TextView) findViewById(R.id.search_status_message);
		list = (ListView) findViewById(android.R.id.list);
		error = (TextView) findViewById(android.R.id.empty);
		attemptSearch();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getSupportMenuInflater().inflate(R.menu.search_results, menu);
		return true;
	}

	private class GetReports extends AsyncTask<Void, Void, Boolean> {
		ArrayList<Incident> locs;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if (reportType.equals("ADMIN")) {
				try {
					locs = webservice.getAdminConditionCannedReport(token,
							eventName, eventYear);

				} catch (TokenInvalidException e) {
					return false;
				}
				return true;
			} else if (reportType.equals("CRE")) {
				try {
					locs = webservice.getCREReport(token, eventName, eventYear);
				} catch (TokenInvalidException e) {
					return false;
				}
				return true;
			}
			return null;
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			showProgress(false);
			if (success) {
				Log.v("SRA", "Was a success");
				if (locs != null || locs.size() != 0) {
					incidents = locs;
					BuildingInfoAdapter adapter = new BuildingInfoAdapter(
							getBaseContext(), locs);
					setListAdapter(adapter);
					list.setOnItemClickListener(new Listener());
					adapter.notifyDataSetChanged();
				} else {
					
					error.setText("No Reports Found");
					error.setVisibility(android.view.View.VISIBLE);
				}
			} else {
				System.out.println("Its over here");
				Intent intent = new Intent(getBaseContext(),
						LoginActivity.class);
				intent.putExtra("LOGGED_OUT", true);
				startActivity(intent);
				finish();
				return;
			}
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mSearchStatusView.setVisibility(View.VISIBLE);
			mSearchStatusMessageView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mSearchStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mSearchFormView.setVisibility(View.VISIBLE);
			mSearchFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mSearchFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mSearchStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mSearchFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	private void attemptSearch() {
		// Show a progress spinner, and kick off a background task to
		// perform the user login attempt.
		mSearchStatusMessageView.setText(R.string.search_progress);
		showProgress(true);
		GetReports getReports = new GetReports();
		getReports.execute((Void) null);

	}

	private class Listener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// TODO Auto-generated method stub
			displayBuildingInfo(incidents.get(arg2));
		}
	}

	public void displayBuildingInfo(final Incident incident) {
		AlertDialog.Builder display = new AlertDialog.Builder(
				SearchResultsActivity.this);
		Log.v("DialogBox", "Attempting to create dialog");
		String[] items;
		if (reportType.equals("ADMIN")) {
			String eventName = "Event Name: " + incident.getEventName(), year = "Event Year: "
					+ eventYear, glc = "GLC: " + incident.getGeoLoc(), address = "Address: "
					+ incident.getBuildingAddress(), state = "State: "
					+ incident.getState(), type = "Type: "
					+ incident.getBuildingType(), pm = "PM: "
					+ incident.getPMAttuid(), assessment = "Assessment: "
					+ incident.getAssessNotes(), status = "Status: "
					+ incident.getIncidentStatus(), damage = "Damage: "
					+ incident.getDamageIndicator(), commercial = "Commercial Power: "
					+ incident.getComPowerIndicator(), onGenerator = "On Generator: "
					+ incident.getOnGeneratorIndicator(), unOccupiable = "Unoccupiable: "
					+ incident.getUnOccupiableIndicator();
			String[] i = { eventName, year, glc, address, state, type, pm,
					assessment, status, damage, commercial, onGenerator,
					unOccupiable };
			items = i;
		} else {
			String eventName = "Event Name: " + incident.getEventName(), date = "Event Year: "
					+ incident.getInitialRptDate(), buildingStatus = "Status: "
					+ incident.getIncidentStatus(), glc = "GLC: "
					+ incident.getGeoLoc(), address = "Address: "
					+ incident.getBuildingAddress(), state = "State: "
					+ incident.getState(), type = "Type: "
					+ incident.getBuildingType(), pm = "PM: "
					+ incident.getPMAttuid(), assessment = "Assessment: "
					+ incident.getAssessNotes(), status = "Status: "
					+ incident.getIncidentStatus();
			String[] i = { eventName, date, buildingStatus, glc, address,
					state, type, pm, assessment, status };
			items = i;
		}
		display.setTitle(incident.getBuildingName())
				.setItems(items, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// do nothing here
					}// End of onClick
				}// End of OnClickListner
				)// End Of setItems
					// Update Button, Launches new activity and then
					// closes dialog
				// End of Set positive Button
				// Exit Button, closes dialog Box
				.setNegativeButton("Exit",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) { //
								// TODO Auto-generated method stub
								// DisplayedInfoDialog.this.getDialog().cancel();
								// } });
							}// End of onClick
						}// End of onClicklistner
				);// End of setNegative button and creation of
					// alertDialog

		Log.v("DialogBox", "Attempting to display");
		// Show Dialog box
		AlertDialog displayInfo = display.create();
		displayInfo.show();
	}
}
